import React, { useLayoutEffect, useEffect, useState } from 'react';
import { Text, ScrollView, router, publishDps, hideMenuButton } from '@ray-js/ray';
import clsx from 'clsx';
import { useDevice, useProps } from '@ray-js/panel-sdk';
import { getCachedSystemInfo } from '@/api/getCachedSystemInfo';
import Strings from '@/i18n';

import { Cell, Slider, Switch, NavBar } from '@ray-js/smart-ui';
import { LampColorSlider } from '@ray-js/components-ty-lamp';
import { decodeScene, encodeScene } from '@/utils';

import { View, Image } from '@/components';

import res from '../../../public/newImage';
import styles from './index.module.less';
import { VoiceList } from '../Home';

// saveCloudDataAsync

const HeaderHeight = 59;

const sysInfo = getCachedSystemInfo();

const getOriginData = (data: Record<string, any>) => {
  return {
    startTime: data.startTime,
    startTimeObj: {
      hour: Math.floor(data.startTime / 60),
      minute: data.startTime % 60,
    },
    music: data.music,
    musicSet: data.musicSet,
    musicSetStr: data.musicSet,
    status: data.status,
    lightMode: data.lightMode,
    lightModeStr: data.lightMode,
    repeat: data.repeat,
    wakeUp: data.wakeUp,
    advanceTime: data.advanceTime,
    voice: data.voice,
    light: data.light,
    colour: data.colour,
    code: data.code,
    lampPower: data.lampPower,
    musicPower: data.musicPower,
    colourBright: data.colourBright,
  };
};

export function ClockEdit({ location }) {
  const { query } = location;

  const sceneStr = useProps(props => props[query.code || 'customize_scene_1']);

  const data = decodeScene(sceneStr);

  const orginData = getOriginData(data);

  useLayoutEffect(() => {
    hideMenuButton();
  }, []);

  const [showTransformBox, setShowTransformBox] = useState(orginData.lampPower);

  const [showTransformVoiceBox, setShowTransformVoiceBox] = useState(true);

  const [scrollEnabled, setScrollEnabled] = useState(true);
  const deviceName = useDevice(d => d?.devInfo?.name);

  const [musicPower, setMusicPower] = useState(orginData.musicPower);

  const [volumeSet, setVolumeSet] = useState(orginData.voice);
  const [volumeSetStr, setVolumeSetStr] = useState(orginData.voice);

  const [brightValue, setBrightValue] = useState(orginData.light);
  const [brightValueStr, setBrightValueStr] = useState(orginData.light);

  const [lightMode, setLightMode] = useState(orginData.lightModeStr);
  const [colour, setColour] = useState(orginData.colour);

  const [colourBright, setColourBright] = useState(orginData.colourBright);

  const [{ musicSet, ringtone }, setMusicSet] = useState({
    musicSet: orginData.musicSetStr,
    ringtone: orginData.music,
  });

  const onClickLeft = () => {
    router.back();
  };

  const CurrentMusic =
    VoiceList[musicSet]?.find(item => item.code === ringtone) || VoiceList.nature[0];

  const saveScene = () => {
    const params = {
      code: query.code || 'customize_scene_1',

      lampPower: showTransformBox,
      lightMode,
      colour,
      brightValue,
      musicPower,
      musicSet,
      ringtone,
      volumeSet,
      colourBright,
    };

    const res = encodeScene(params);

    publishDps({
      [params.code]: res,
    });

    router.back();
  };

  const getLightSliderValue = () => {
    if (lightMode === 'breathe_lamp') return 1000;
    if (lightMode === 'color_ligth') return colourBright;
    if (lightMode === 'lighting_lamp') return brightValue;

    return 10;
  };

  const getLightSliderMinValue = () => {
    if (lightMode === 'lighting_lamp') return 10;
    return 0;
  };

  const getLightSliderDisable = () => {
    if (!showTransformBox) return true;
    if (lightMode === 'breathe_lamp') return true;
    return false;
  };

  useEffect(() => {
    setBrightValueStr(getLightSliderValue());
  }, [brightValue, colourBright, lightMode]);

  return (
    <View className={styles.view}>
      <NavBar
        title={deviceName}
        className={styles.navBar}
        customClass={styles.borBot}
        slot={{
          left: (
            <View className={styles.tabTopIconWrapLeft} onClick={onClickLeft}>
              {['back'].map(item => (
                <Image src={`/newImage/${item}.png`} key={item} />
              ))}
            </View>
          ),
          right: (
            <View className={styles.tabTopIconWrap} onClick={saveScene}>
              <Text>{Strings.getLang('save')}</Text>
            </View>
          ),
        }}
      />
      <ScrollView
        scrollY={scrollEnabled}
        refresherTriggered
        className={clsx(styles.slideUpContent)}
        style={{
          height: `calc(100vh - ${HeaderHeight}px - ${sysInfo.statusBarHeight}px)`,
        }}
      >
        <View
          style={{
            marginTop: 10,
          }}
        >
          <View className={styles.card}>
            <View className={styles.cardContent}>
              <View className={styles.musicContent}>
                <View className={styles.currentMusic}>
                  {/* <Image src={CurrentMusic.picActive} className={styles.current} /> */}
                  <Image
                    src={musicPower ? res.currentMusic : res.mute}
                    className={styles.current}
                    style={{
                      width: '72rpx',
                      height: '78rpx',
                    }}
                  />
                  <Text className={styles.currentMusicName}>{CurrentMusic?.name}</Text>
                </View>
                <View className={styles.controlBox}>
                  <Image
                    src={res.next}
                    className={styles.control}
                    onClick={() => {
                      const list = VoiceList?.[musicSet];

                      const currentIndex = list.findIndex(item => item.code === ringtone);

                      if (currentIndex === 0) {
                        setMusicSet({
                          musicSet,
                          ringtone: list[list.length - 1].code,
                        });
                      } else {
                        setMusicSet({
                          musicSet,
                          ringtone: list[currentIndex - 1].code,
                        });
                      }
                    }}
                  />
                  <Image
                    src={musicPower ? res.pause : res.play}
                    className={styles.play}
                    onClick={() => {
                      setMusicPower(!musicPower);
                    }}
                  />
                  <Image
                    src={res.prev}
                    className={styles.control}
                    onClick={() => {
                      const list = VoiceList?.[musicSet];

                      const currentIndex = list.findIndex(item => item.code === ringtone);

                      if (currentIndex === list.length - 1) {
                        setMusicSet({
                          musicSet,
                          ringtone: list[0].code,
                        });
                      } else {
                        setMusicSet({
                          musicSet,
                          ringtone: list[currentIndex + 1].code,
                        });
                      }
                    }}
                  />
                </View>
              </View>

              <View className={styles.sliderBox}>
                <Image src={res.voice} className={styles.sliderPic} />
                <Slider
                  maxTrackHeight="18rpx"
                  minTrackHeight="18rpx"
                  thumbHeight="20px"
                  thumbWidth="20px"
                  max={100}
                  min={1}
                  step={1}
                  value={volumeSet}
                  maxTrackColor="#052F46"
                  minTrackColor="#E2E742"
                  thumbColor="#fff"
                  onBeforeChange={() => {
                    setScrollEnabled(false);
                  }}
                  // onChange={value => {
                  //   setVolumeSetStr(value);
                  // }}
                  onAfterChange={value => {
                    setScrollEnabled(true);
                    setVolumeSet(value);
                    setVolumeSetStr(value);
                  }}
                  style={{
                    width: `550rpx`,
                  }}
                />
                <View className={styles.sliderText}>
                  <Text>{volumeSetStr}%</Text>
                </View>
              </View>

              <View className={styles.sliderBox}>
                <Image src={res.light} className={styles.sliderPic} />
                <Slider
                  maxTrackHeight="18rpx"
                  minTrackHeight="18rpx"
                  thumbHeight="20px"
                  thumbWidth="20px"
                  maxTrackColor="#052F46"
                  minTrackColor={getLightSliderDisable() ? '#E2E74250' : '#E2E742'}
                  thumbColor="#fff"
                  max={1000}
                  min={getLightSliderMinValue()}
                  step={10}
                  value={getLightSliderValue()}
                  disabled={getLightSliderDisable()}
                  onBeforeChange={() => {
                    setScrollEnabled(false);
                  }}
                  onAfterChange={value => {
                    setScrollEnabled(true);

                    if (lightMode === 'color_ligth') {
                      setColourBright(value);
                    } else {
                      setBrightValue(value);
                    }
                  }}
                  style={{
                    width: `550rpx`,
                  }}
                />
                <View className={styles.sliderText}>
                  <Text>{(brightValueStr / 10).toFixed(0)}%</Text>
                </View>
              </View>
            </View>
          </View>

          <View className={styles.customCellBox}>
            <Cell
              title={Strings.getLang('lamp')}
              icon={res.lamp}
              customClass={clsx(styles.cellNoBtm, styles.transformCell)}
            >
              <Switch
                checked={showTransformBox}
                size="24px"
                onChange={() => {
                  setShowTransformBox(!showTransformBox);
                }}
              />
            </Cell>
            <View
              className={clsx(styles.transformBox, showTransformBox && styles.transformBoxActive)}
            >
              <View className={styles.wrapper}>
                {['lighting_lamp', 'color_ligth', 'breathe_lamp'].map(item => {
                  return (
                    <View
                      onClick={() => {
                        setLightMode(item);
                      }}
                      key={item}
                      className={clsx(styles.tab, lightMode === item && styles.tabActive)}
                    >
                      <Text>{Strings.getLang(item)}</Text>
                    </View>
                  );
                })}
              </View>
              <View
                style={{
                  marginTop: 20,
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                }}
              >
                {lightMode === 'color_ligth' && (
                  <LampColorSlider
                    value={colour}
                    trackStyle={{
                      height: '10px',
                      width: `640rpx`,
                      borderRadius: '5px',
                      marginTop: 20,
                    }}
                    thumbStyle={{
                      height: '20px',
                      width: '20px',
                      borderRadius: '10px',
                      borderColor: 'transparent',
                    }}
                    onTouchStart={() => setScrollEnabled(false)}
                    onTouchEnd={val => {
                      setScrollEnabled(true);
                      setColour(val);
                    }}
                  />
                )}
              </View>
            </View>
          </View>

          <View className={styles.customCellBox}>
            <Cell
              title={Strings.getLang('voiceType')}
              customClass={styles.transformCell}
              isLink
              icon={res.voiceType}
              // onClick={() => {
              //   setShowTransformVoiceBox(!showTransformVoiceBox);
              // }}
            />

            <View
              className={clsx(
                styles.transformBox,
                showTransformVoiceBox && styles.transformBoxActive
              )}
            >
              <View className={styles.wrapper}>
                {['nature', 'environment', 'thing', 'sleep'].map(item => {
                  return (
                    <View
                      onClick={() => {
                        setMusicSet({
                          musicSet: item,
                          ringtone: 'ringtone_1',
                        });
                      }}
                      key={item}
                      className={clsx(styles.tabSmall, musicSet === item && styles.tabActive)}
                    >
                      <Text>{Strings.getLang(item)}</Text>
                    </View>
                  );
                })}
              </View>

              <View className={styles.voiceContent}>
                {VoiceList?.[musicSet].map(item => {
                  const active = musicSet === item.type && item.code === ringtone && musicPower;
                  return (
                    <View
                      key={item.code}
                      onClick={() => {
                        if (active) {
                          setMusicPower(false);
                          return;
                        }

                        setMusicSet(x => ({
                          musicSet: x.musicSet,
                          ringtone: item.code,
                        }));
                        setMusicPower(true);
                        // publishDps({
                        //   ringtone: item.code,
                        // });
                      }}
                      className={styles.voiceItemBox}
                    >
                      <Image
                        src={active ? item.picActive : item.pic}
                        className={styles.voiceItem}
                      />
                      <Text className={styles.voiceItemName}>{item?.name}</Text>
                    </View>
                  );
                })}
              </View>
            </View>
          </View>
        </View>
      </ScrollView>
    </View>
  );
}

export default ClockEdit;
